import router from './router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from './store'
import useUserStore from './store/modules/user'
const userStore = useUserStore(pinia)

//全局路由守卫
//全局前置守卫
router.beforeEach((to, from, next) => {
  nprogress.start()
  if (userStore.token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (userStore.userName) {
        next()
      } else {
        userStore
          .Init()
          .then(t => {
            next()
          })
          .catch(async err => {
            await userStore.logout()
            next({ path: '/login' })
          })
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
//全局后置守卫
router.afterEach((from, to) => {
  nprogress.done()
})
